package com.jcbase.model;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections4.CollectionUtils;

import com.google.common.collect.Lists;
import com.jcbase.core.auth.common.CONST;
import com.jcbase.core.model.Condition;
import com.jcbase.core.model.Operators;
import com.jcbase.core.util.CommonUtils;
import com.jcbase.core.util.IWebUtils;
import com.jcbase.core.view.InvokeResult;
import com.jcbase.core.view.ZtreeView;
import com.jcbase.model.base.BaseSysObjGroup;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

/**
 * Generated by JFinal.
 */
@SuppressWarnings("serial")
public class SysObjGroup extends BaseSysObjGroup<SysObjGroup> {
    public static final SysObjGroup me = new SysObjGroup();

    public InvokeResult getZtreeViewList(HttpServletRequest request) {
	HashMap<String, List<SysObj>> groupTree = new HashMap<String, List<SysObj>>();

	// 根据角色获取所有用的组信息
	SysUser user = IWebUtils.getCurrentSysUser(request);
	List<SysUserRole> list = SysRole.me.getRole(request);
	List<SysObjGroup> pageInfo;
	if (SysRole.me.checkIsAdmin(list)) {
	    pageInfo = SysObjGroup.me.getAllList();
	} else {
	    pageInfo = SysObjGroup.me.find("select * from sys_obj_group where create_user_id = " + user.getId());
	}
	// 根据组获取列表
	for (SysObjGroup sysGroup : pageInfo) {
	    List<SysObj> userList = SysObj.me.find("select * from sys_obj_group where group_id = " + sysGroup.getId());
	    if (sysGroup.getPId() == null) {
		groupTree.put(sysGroup.getName() + "_" + sysGroup.getId() + "_" + CONST.ROOT_SIZE, userList);
	    } else {
		groupTree.put(sysGroup.getName() + "_" + sysGroup.getId() + "_" + sysGroup.getPId(), userList);
	    }
	}

	groupTree.put("root", SysObj.me.find("select * from sys_obj where ISNULL(group_id)"));
	List<ZtreeView> ztreeViews = new ArrayList<ZtreeView>();
	ZtreeView zt = new ZtreeView(CONST.ROOT_SIZE, null, "root", true);

	zt.setType("root");
	zt.setIcon("/res/image/house.ico");
	ztreeViews.add(zt);
	for (String key : groupTree.keySet()) {
	    if (key.equals("root")) {
		List<SysObj> rootList = groupTree.get(key);
		if (rootList != null && !rootList.isEmpty()) {
		    for (SysObj sysObj : rootList) {
			// 如果被分组
			ZtreeView childTree = new ZtreeView();
			childTree.setpId(CONST.ROOT_SIZE);
			childTree.setName(sysObj.getName());
			childTree.setId(CONST.LEAF_SIZE);
			childTree.setOpen(true);
			childTree.setType("obj");
			childTree.setIcon("/res/image/user.ico");
			
			childTree.setObjId(String.valueOf(sysObj.getId()));
			ztreeViews.add(childTree);
		    }
		}
	    } else {
		String groupName = key.split("_")[0];
		String groupId = key.split("_")[1];
		String groupPid = key.split("_")[2];
		ZtreeView ztreeView = new ZtreeView();
		ztreeView.setName(groupName);
		ztreeView.setId(Integer.parseInt(groupId));
		ztreeView.setpId(Integer.parseInt(groupPid));
		ztreeView.setOpen(true);
		ztreeView.setType("group");
		ztreeView.setIcon("/res/image/folder.ico");
		ztreeView.setObjId(groupId);
		ztreeViews.add(ztreeView);
		List<SysObj> objList = groupTree.get(key);
		// 添加子节点
		if (objList != null && !objList.isEmpty()) {
		    for (SysObj sysObj : objList) {
			// 如果被分组
			if (!"".equals(sysObj.getGroupId()) && sysObj.getGroupId() != null) {
			    ZtreeView childTree = new ZtreeView();
			    childTree.setpId(sysObj.getGroupId());
			    childTree.setName(sysObj.getName());
			    childTree.setId(CONST.LEAF_SIZE);
			    childTree.setIcon("/res/image/user.ico");
			    childTree.setOpen(true);
			    childTree.setType("obj");
			    childTree.setObjId(String.valueOf(sysObj.getId()));
			    ztreeViews.add(childTree);
			} else {
			    continue;
			}
		    }
		}
	    }
	}
	return InvokeResult.success(JsonKit.toJson(ztreeViews));
    }

    public InvokeResult getZtreeViewList(Integer roleId) {
	List<SysObj> SysObjlist = SysObj.me.getAllList();
	List<Record> record = Db.find("select * from sys_role_obj where role_id= " + roleId);
	List<Integer> list = Lists.newArrayList();
	if (!CollectionUtils.isEmpty(record)) {
	    for (Record RoleObj : record) {
		list.add(RoleObj.getInt("obj_id"));
	    }
	}
	List<ZtreeView> ztreeViews = new ArrayList<ZtreeView>();
	ztreeViews.add(new ZtreeView(10000, null, "资源列表", true));
	for (SysObj sysObj : SysObjlist) {
	    ZtreeView ztreeView = new ZtreeView();
	    ztreeView.setId(sysObj.getId());
	    ztreeView.setObjId(String.valueOf(sysObj.getId()));
	    ztreeView.setName(sysObj.getName());
	    ztreeView.setOpen(true);
	    ztreeView.setType("obj");
	    if (sysObj.getInt("pid") == null) {
		ztreeView.setpId(10000);
	    } else {
		ztreeView.setpId(sysObj.getInt("pid"));
	    }
	    if (list.contains(sysObj.getId())) {
		ztreeView.setChecked(true);
	    } else {
		ztreeView.setChecked(false);
	    }
	    ztreeViews.add(ztreeView);
	}
	return InvokeResult.success(JsonKit.toJson(ztreeViews));
    }

    public InvokeResult delete(String idStrs) {
	List<Integer> ids = CommonUtils.getIntegerListByStrs(idStrs);
	Set<Condition> conditions = new HashSet<Condition>();
	conditions.add(new Condition("id", Operators.IN, ids));
	this.delete(conditions);
	return InvokeResult.success();
    }

    public InvokeResult updateUserGroup(String ObjId, Integer groupId) {
	if (CommonUtils.isNotEmpty(ObjId)) {
	    for (String id : ObjId.split(",")) {
		if (CommonUtils.isNotEmpty(id)) {
		    Record user = Db.findById("sys_obj", id).set("group_id", groupId);
		    Db.update("sys_obj", user);
		}
	    }
	}
	return InvokeResult.success();
    }

    public InvokeResult addSave(Integer pid, String name) {
	if (pid < 0) {
	    new SysObjGroup().set("name", name).set("create_time", new Date()).save();
	} else {
	    new SysObjGroup().set("name", name).set("p_id", pid).set("create_time", new Date()).save();
	}
	return InvokeResult.success();
    }

    public InvokeResult updateSave(Integer gid, String name) {
	SysObjGroup group = this.findById(gid);
	group.set("name", name).update();
	return InvokeResult.success();
    }

    public InvokeResult deleteUserGroup(String objs) {
	if (CommonUtils.isNotEmpty(objs)) {
	    for (String id : objs.split(",")) {
		if (CommonUtils.isNotEmpty(id)) {
		    Record user = Db.findById("sys_obj", id).set("group_id", null);
		    Db.update("sys_obj", user);
		}
	    }
	}
	return InvokeResult.success();
    }
}
